package com.baidu.mail.service.impl;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baidu.mail.dao.MailDao;
import com.baidu.mail.entity.MailAccount;
import com.baidu.mail.service.MailService;
import com.baidu.util.ExcelUtil;

@Service
public class MailServiceImpl implements MailService{

	@Autowired
	private MailDao dao ;
	
	public void poiUploadMail(File file) {
		ExcelUtil eu = new ExcelUtil();
		try {
			eu.setExcelPath(file.getAbsolutePath());
			eu.setStartReadPos(2);
			List<Row> list = eu.readExcel();
			List<MailAccount> accounts = new ArrayList<MailAccount>();
			for (Row row : list) {
				MailAccount account = new MailAccount();
				account.setId((int)row.getCell(0).getNumericCellValue());
				account.setMail(row.getCell(3).getStringCellValue());
				account.setName(row.getCell(1).getStringCellValue());
				account.setPassword(row.getCell(4).getStringCellValue());
				account.setPhone(new DecimalFormat("#").format(row.getCell(2).getNumericCellValue()));
				accounts.add(account);
			}
			dao.saveMail(accounts);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Map<String, Object> findByPage(Integer page, Integer rows) {
		if(page!=null&&rows!=null){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("start", (page-1)*rows);
			map.put("end", page*rows);
			List<MailAccount> accounts = dao.findByPage(map);
			int count = dao.getListCount();
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("total", count);
			data.put("rows", accounts);
			return data;
		}
		return null;
	}

}
